<template>
  <a-modal
    :title="title"
    :width="700"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">


        <a-row>
          <a-col span="24">
            <a-form-item label="文件名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input
                  disabled
                  placeholder="请输入文件名称"
                  v-decorator="['fileName', validatorRules.fileName ]"/>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col span="24">
            <a-form-item label="文件描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea
                placeholder="请输入文件描述"
                v-decorator="['describe', validatorRules.describe ]" :autoSize ="{ minRows: 3, maxRows: 8 }"/>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col span="24">
            <a-form-item label="附件上传" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-upload
                v-if="isRender"
                name="file"
                :headers="headers"
                :data="fileData"
                :defaultFileList="fileList"
                :action="uploadUrl"
                :remove="beforeRemove"
                :beforeUpload="beforeUpload"
                @change="UploadhandleChange"
                v-decorator="['uploadPath', validatorRules.uploadPath]"
                style="display: inline">
                <a-button v-if="!fileList.length">
                  <a-icon type="upload" />
                  选择导入文件
                </a-button>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import {Modal} from 'ant-design-vue'
  import BASE_URL from '../../../../config'
  import Vue from 'vue'
  import { ACCESS_TOKEN, USER_INFO } from  "@/store/mutation-types"
  import pick from 'lodash.pick'
  import { postAction } from '@/api/manage'
  export default {
    name: "AddLabpModal",
    components:{
    
    },
    data() {
      return {
        fileSize: '',
        isRender: false,
        uploadUrl: BASE_URL + '/article/upload',
        headers: {
          'token': Vue.ls.get(ACCESS_TOKEN)
        },
        // 上传附带参数
        fileData: {
          createBy: Vue.ls.get(USER_INFO).username || '游客',
        },
        fileList: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 },
        },
        title: "操作",
        visible: false,
        disable: true,
        model: {},
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          fileName: {},
          describe: {},
          uploadPath: {
            getValueFromEvent: this.normFile,
            rules: [{required: true, message: '请上传文件!' }]}
        }
      }
    },
    created() {
    },
    methods: {
      normFile(e) {
        if (Array.isArray(e)) {
          return e;
        }
        return e && e.fileList;
      },
      beforeRemove(file) {
        let self = this
        let url
        if (file.response) {
          url = file.response.result.fileurl
        } else {
          url = file.url
        }
        let index
        for(let x in this.fileList) {
          if(this.fileList[x].url == url) {
            index = x
          }
        }
        return new Promise((resolve, reject) => {
          this.$confirm({
            title: '确认要移除此文件?',
            onOk() {
              self.fileList.splice(index,1)
              self.form.setFieldsValue({
                'uploadPath': undefined
              })
              resolve()
            },
            onCancel() {
              resolve(false)
            }
          })
        })
      },
      UploadhandleChange(info) {
        if (info.file.status === 'done') {
          if(info.file.response.code != 0) {
            if (info.file.response.code == 401){
              if(info.file.response.msg.includes("invalid token")) {
                Modal.error({
                  title: '登录已过期',
                  content: '很抱歉，登录已过期，请重新登录',
                  okText: '重新登录',
                  mask: false,
                  onOk: () => {
                    Vue.ls.remove(ACCESS_TOKEN)
                    Vue.ls.remove(USER_INFO)
                    window.location.href="/"
                  }
                })
              } else {
                this.$message.error(`${info.file.name} ${info.file.response.msg}.`)
              }
            }
          } else {
            this.fileList.push({
              uid: this.fileList.length + 1,
              name: info.file.response.result.filename,
              status: 'done',
              url: info.file.response.result.fileurl,
            })
            this.form.setFieldsValue({
              'fileName': info.file.response.result.filename
            })
          }          
          this.$message.success('上传成功!')
        } else if (info.file.status === 'error') {
          if (info.file.response.status === 500) {
            this.$message.error(`文件上传失败: ${info.file.msg} `);
          } else {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                Vue.ls.remove(ACCESS_TOKEN)
                Vue.ls.remove(USER_INFO)
                window.location.href="/"
                // window.location.reload()
              }
            })
          }
        }
      },
      beforeUpload(file) {
        let size = file.size / (1024 * 1024)
        this.fileSize = size.toFixed(2)
        return true
      },
      add() {
        this.disable = false;
        this.edit({});
      },
      edit(record) {
        this.form.resetFields();
        this.model = Object.assign({}, record)
        if(record.fileurl) {
          this.fileList = [
            {
              uid: '1',
              name: record.filename,
              url: record.fileurl,
              status: 'done'
            }
          ]
        }
        this.model.uploadPath = this.fileList
        this.visible = true;
        this.$nextTick(() => {
          this.isRender = true
          this.form.setFieldsValue(pick(this.model, 'fileName', 'describe', 'uploadPath'))
        });
      },
      close() {
        this.$emit('close');
        this.visible = false;
        this.disable = true;
        this.fileList = []
        this.fileSize = ''
        this.isRender = false
      },
      handleOk() {
        let self = this;
        if(this.fileList.length) {
          self.form.setFieldsValue({
            'uploadPath': this.fileList
          })
        } else {
          self.form.setFieldsValue({
            'uploadPath': undefined
          })
        }
        // 触发表单验证
        this.form.validateFields((err, value) => {
          if (!err) {
            self.confirmLoading = true
            let formData = Object.assign(self.model, value);
            formData.filesize = self.fileSize + 'MB'
            formData.filename = self.fileList[0].name
            formData.fileurl = self.fileList[0].url
            delete formData.uploadPath
            let url 
            if(self.model.id) {
              url = '/download/update'
            } else {
              url = '/download/save'
            }
            postAction(url, formData).then(res => {
              if(res.code == 0) {
                self.$message.success(res.msg)
                self.confirmLoading = false
                self.close()
                self.$emit('ok')
              } else {
                self.$message.error(res.msg)
                  self.confirmLoading = false
              }
            })
          }
        })
      },
      handleCancel() {
        this.close()
      }
    }
  }
</script>

<style lang="less" scoped>

</style>